package com.cyan.teamquestionnaire.controller;

import com.cyan.teamquestionnaire.beans.HttpResponseEntity;
import com.cyan.teamquestionnaire.beans.PageInfo;
import com.cyan.teamquestionnaire.entity.SecurityQuestion;
import com.cyan.teamquestionnaire.entity.User;
import com.cyan.teamquestionnaire.service.QuestionnaireService;
import com.cyan.teamquestionnaire.service.SecurityQuestionService;
import com.cyan.teamquestionnaire.service.UserService;
import com.cyan.teamquestionnaire.utils.Constants;
import com.cyan.teamquestionnaire.utils.MessageUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

@RestController
public class UserController {

    @Resource
    private UserService userService;
    // 返回信息
    @Resource
    private HttpResponseEntity httpResponseEntity;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    SecurityQuestionService questionService;

    @Resource
    QuestionnaireService questionnaireService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public HttpResponseEntity logIn(@RequestBody User user) {
        User u = userService.selectByName(user.getName());
        httpResponseEntity.setData(u);
        httpResponseEntity.setCode(Constants.EXIST_CODE);
        httpResponseEntity.setMessage(Constants.LOGIN_USERNAME_MESSAGE);
        if (u != null) {
            if (u.getPasswd().equals(user.getPasswd())) {
                httpResponseEntity.setCode(Constants.SUCCESS_CODE);
                httpResponseEntity.setMessage(Constants.LOGIN_MESSAGE);
                httpResponseEntity.setData(u);
            } else {
                httpResponseEntity.setMessage(Constants.LOGIN_PASSWORD_MESSAGE);
            }
        }
        return httpResponseEntity;
    }

    // 租户和管理员的用户管理功能，该方法拉取管理的所有人员
    //传入name和level
    @RequestMapping(value = "/allUser", method = RequestMethod.POST)
    public HttpResponseEntity allUser(@RequestBody PageInfo<User> pageInfo) {

        pageInfo = userService.getManagedUsers(pageInfo);
        httpResponseEntity.setData(pageInfo);
        httpResponseEntity.setCode(Constants.SUCCESS_CODE); // 一定是查询成功的
        httpResponseEntity.setMessage(Constants.STATUS_MESSAGE);
        return httpResponseEntity;
    }

    // 创建用户，进行判断。如果是租户，那么直接创建，如果是用户，那么需要加入租户表中
    //传入用户的信息以及租户的名字tenantName
    @RequestMapping(value = "/createUser", method = RequestMethod.POST)
    public HttpResponseEntity createUser(@RequestBody Map<String, Object> map) {

        String name = (String) map.get("name");
        String passwd = (String) map.get("passwd");
        String tel = (String) map.get("tel");
        Integer level = Integer.parseInt((String) map.get("level"));

        User user = new User(level, name, passwd, tel, 0);
        httpResponseEntity.setCode(Constants.EXIST_CODE);
        if (userService.selectByName(user.getName()) != null) {
            httpResponseEntity.setMessage(Constants.CREATE__USERNAME_MESSAGE);
        } else if (userService.selectByTel(user.getTel()) != null) {
            httpResponseEntity.setMessage(Constants.CREATE_TEL_MESSAGE);
        } else {
            if (level == 3) {
                Integer count = Integer.parseInt((String) map.get("count"));
                user.setCount(count);
                String tenantName = (String) map.get("tenantName");
                userService.tenantAddUser(tenantName, user.getName());
            }
            userService.createUser(user);
            httpResponseEntity.setCode(Constants.SUCCESS_CODE);
            httpResponseEntity.setMessage(Constants.CREATE_MESSAGE);
        }
        return httpResponseEntity;
    }

    // 删除用户,传入用户name,level
    //由于是从列表中选择，所以不存在数据错误情况
    @RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
    public HttpResponseEntity deleteUser(@RequestBody User user) {
        //判断删除的是租户
        if (user.getLevel() == 2) {
            //如果还有用户
            if (userService.tenantHasUser(user.getName()).size() != 0) {
                httpResponseEntity.setCode(Constants.EXIST_CODE);
                httpResponseEntity.setMessage(Constants.DeleteFail_Tenant_HasUser);
                return httpResponseEntity;
            }
        }
        //删除的是用户
        if (user.getLevel() == 3) {
            //如果还有问卷
            if (questionnaireService.selectByCreatorName(user.getName()).size() != 0) {
                httpResponseEntity.setCode(Constants.EXIST_CODE);
                httpResponseEntity.setMessage(Constants.DeleteFail_User_HasQuestionnaire);
                return httpResponseEntity;
            }
            userService.tenantDelteUser(user.getName());

        }
        userService.deleteUser(user);
        httpResponseEntity.setCode(Constants.SUCCESS_CODE);
        httpResponseEntity.setMessage(Constants.DELETE_Q_TRUE);
        return httpResponseEntity;
    }

    // 获得个人信息--name
    @RequestMapping(value = "/getUpdate", method = RequestMethod.GET)
    public HttpResponseEntity getUpdate(String name) {
        User user = userService.selectByName(name);
        if (user == null) {
            httpResponseEntity.setCode(Constants.EXIST_CODE);
            httpResponseEntity.setMessage(Constants.LOGIN_USERNAME_MESSAGE);
        } else {
            httpResponseEntity.setData(user);
            httpResponseEntity.setCode(Constants.SUCCESS_CODE);
            httpResponseEntity.setMessage(Constants.STATUS_MESSAGE);
        }
        return httpResponseEntity;
    }

    // 获得个人信息--tel
    @RequestMapping(value = "/userByTel", method = RequestMethod.POST)
    public HttpResponseEntity userByTel(String tel) {
        User user = userService.selectByTel(tel);
        if (user == null) {
            httpResponseEntity.setCode(Constants.EXIST_CODE);
            httpResponseEntity.setMessage(Constants.USER_TEL);
        } else {
            httpResponseEntity.setData(user);
            httpResponseEntity.setCode(Constants.SUCCESS_CODE);
            httpResponseEntity.setMessage(Constants.STATUS_MESSAGE);
        }
        return httpResponseEntity;
    }

    // 修改个人信息,可修改level  passwd  count 要传入name
//    传过来判断手机号是否改变，改变了 判断重复就更新   不改变 就不更新
    @RequestMapping(value = "/editUser", method = RequestMethod.POST)
    public HttpResponseEntity editUser(@RequestBody User user) {

        User u = userService.selectByTel(user.getTel());
        if (u == null) {
            //手机号修改了 而且没有重复的,进行手机号修改
            userService.modifyUser(user);
            userService.modifyUserTel(user);
            httpResponseEntity.setMessage(Constants.MODIFY_SUCCESS);
            httpResponseEntity.setCode(Constants.SUCCESS_CODE);
        } else {
            if (u.getName() != user.getName()){//手机号修改了。但是手机号已经注册了
                httpResponseEntity.setMessage(Constants.MODIFY_FAILE);
                httpResponseEntity.setCode(Constants.EXIST_CODE);
            }
            else {//发现手机号没改
                userService.modifyUser(user);
                httpResponseEntity.setMessage(Constants.MODIFY_SUCCESS);
                httpResponseEntity.setCode(Constants.SUCCESS_CODE);
            }
        }




        return httpResponseEntity;
    }

    // 发送验证码,处理前端请求验证码（已完成）
    @RequestMapping(value = "/getCode", method = RequestMethod.GET)
    public HttpResponseEntity getCode(String tel) {
        // 后端没有手机号格式校验，vue前端能够处理，我就不重复了
        MessageUtils.execute(tel, redisTemplate);
        httpResponseEntity.setCode(Constants.SUCCESS_CODE);
        httpResponseEntity.setMessage(Constants.CODE_IDENTIFY_SUCCESS);
        return httpResponseEntity;
    }

    // 手机登录,前端传过来手机号--tel和验证码--code（已完成）
    @RequestMapping(value = "/telLogin", method = RequestMethod.POST)
    public HttpResponseEntity telLogin(@RequestBody Map<String, Object> data) {
        // 现在redis已经缓存了<phoneNum, identifyCode>键值对，直接拿来用
        String tel = (String) data.get("tel");
        String code = (String) data.get("code");
        httpResponseEntity = identifyCode(code, tel);// 校验验证码
        if (httpResponseEntity.getCode().equals(Constants.EXIST_CODE)) return httpResponseEntity;

        User u = userService.selectByTel(tel);
        if (u == null) {
            httpResponseEntity.setCode(Constants.EXIST_CODE);
            httpResponseEntity.setMessage(Constants.USER_TEL);
        } else {
            httpResponseEntity.setMessage(Constants.LOGIN_MESSAGE);
            httpResponseEntity.setCode(Constants.SUCCESS_CODE);
            httpResponseEntity.setData(u);
        }
        return httpResponseEntity;
    }

    /**
     * 注册账户, 身份-level, 用户名-name, 密码-passwd, 电话-tel, 验证码-code
     * 默认前端对数据合法性进行处理了
     */
    @RequestMapping(value = "/signIn", method = RequestMethod.POST)
    public HttpResponseEntity signIn(@RequestBody Map<String, Object> map) {
        // 获取前端数据
        Integer level = Integer.parseInt((String) map.get("level"));
        String name = (String) map.get("name");
        String passwd = (String) map.get("passwd");
        String tel = (String) map.get("tel");
        String code = (String) map.get("code");
        User user = new User(level, name, passwd, tel, 0);

        httpResponseEntity = identifyCode(code, tel); // 校验验证码
        if (httpResponseEntity.getCode().equals(Constants.EXIST_CODE)) {// 验证码验证错误
            return httpResponseEntity;
        }
        int res = userService.createUser(user);
        httpResponseEntity.setCode(Constants.EXIST_CODE);
        if (res == 1) httpResponseEntity.setMessage(Constants.CREATE_DATA_MESSAGE);
        else if (res == 2) httpResponseEntity.setMessage(Constants.CREATE__USERNAME_MESSAGE);
        else if (res == 3) httpResponseEntity.setMessage(Constants.CREATE_TEL_MESSAGE);
        else {
            httpResponseEntity.setCode(Constants.SUCCESS_CODE);
            httpResponseEntity.setMessage(Constants.CREATE_MESSAGE);
        }
        return httpResponseEntity;
    }

    /**
     * 验证密保问题，验证成功后前端弹出修改密码的窗口
     * 密保验证成功后，我这直接返回一个User对象，找回的密码就放在这里面
     * 传入用户名--name，答案--answer，新密码--passwd
     */
    @RequestMapping(value = "/identifySq", method = RequestMethod.POST)
    public HttpResponseEntity passwdRecoverBySq(@RequestBody Map<String, Object> map) {
        // 获取密保答案
        SecurityQuestion tmp = questionService.getQuestionByName((String) map.get("name"));
        httpResponseEntity.setCode(Constants.EXIST_CODE);
        if (tmp == null) { // 还没有设置密保问题
            httpResponseEntity.setMessage(Constants.SECURITY_NO_EXITS);
        } else if (tmp.getAnswer().equals(map.get("answer").toString())) {// 密保答案相同
            User u = userService.selectByName((String) map.get("name"));
            u.setPasswd((String) map.get("passwd"));
            userService.modifyUser(u);// 修改密码
            httpResponseEntity.setCode(Constants.SUCCESS_CODE);
            httpResponseEntity.setMessage(Constants.SECURITY_IDENTIFY_TRUE);
            httpResponseEntity.setData(u);
        } else {
            httpResponseEntity.setMessage(Constants.SECURITY_IDENTIFY_ERROR);
        }
        return httpResponseEntity;
    }

    /**
     * 通过手机号+验证码找回密码
     * 传入name，是为了判断他传的tel是不是自己的tel
     *
     * @param map 传入参数：tel, code, passwd(新）
     */
    @RequestMapping(value = "/identifyTel", method = RequestMethod.POST)
    public HttpResponseEntity passwdRecoverByTel(@RequestBody Map<String, Object> map) {
        String tel = (String) map.get("tel");
        String passwd = (String) map.get("passwd");
        String code = (String) map.get("code");
        User user = userService.selectByTel(tel);
        if (user == null) {
            httpResponseEntity.setData(Constants.EXIST_CODE);
            httpResponseEntity.setMessage(Constants.USER_TEL);
            return httpResponseEntity;
        }

        user.setPasswd(passwd); // 新密码

        httpResponseEntity = identifyCode(code, tel); // 先判断验证码
        if (httpResponseEntity.getCode().equals(Constants.EXIST_CODE)) return httpResponseEntity;// 验证码失败
        // 手机号不是自己的
        userService.modifyUser(user);// 修改密码
        httpResponseEntity.setMessage(Constants.MODIFY_SUCCESS);
        return httpResponseEntity;
    }

    // 校验验证码
    private HttpResponseEntity identifyCode(String code, String tel) {
        String redisKey = "VERIFATIONCODE:CODE:" + tel;
        String realCode = (String) redisTemplate.opsForValue().get(redisKey);

        httpResponseEntity.setCode(Constants.EXIST_CODE);
        if (realCode == null) {// 验证码过期
            httpResponseEntity.setMessage(Constants.CODE_EXPIRE);
        } else if (!realCode.equals(code)) { // 验证码不相同
            httpResponseEntity.setMessage(Constants.CODE_FALSE);
        } else {
            httpResponseEntity.setCode(Constants.SUCCESS_CODE);
        }
        return httpResponseEntity;
    }

    /**
     * 查询这个租户创建的所有用户
     * 传入租户名字以及要进行查询的query信息————分页
     */
    @RequestMapping(value = "/tenantCreateUserY", method = RequestMethod.POST)
    public HttpResponseEntity tenantCreateUserY(@RequestBody PageInfo<User> pageInfo) {
        pageInfo = userService.tenantCreateUser(pageInfo);
        httpResponseEntity.setData(pageInfo);
        httpResponseEntity.setCode(Constants.SUCCESS_CODE); // 一定是查询成功的
        httpResponseEntity.setMessage(Constants.STATUS_MESSAGE);
        return httpResponseEntity;
    }

    /**
     * 查询所有的答者
     * 传入要进行查询的query信息————分页
     */
    @RequestMapping(value = "/selectAllAnswererY", method = RequestMethod.POST)
    public HttpResponseEntity selectAllAnswererY(@RequestBody PageInfo<User> pageInfo) {
        pageInfo = userService.selectAllAnswerer(pageInfo);
        httpResponseEntity.setData(pageInfo);
        httpResponseEntity.setCode(Constants.SUCCESS_CODE); // 一定是查询成功的
        httpResponseEntity.setMessage(Constants.STATUS_MESSAGE);
        return httpResponseEntity;
    }


    /**
     * 添加用户也可以通过答者列表（level=4 进行添加，授权为3）进行批量添加
     * 由于是从答者界面进行选取的，所以一定成功！
     * 传入tenantName，userName,count
     */
    @RequestMapping(value = "/tenantCreateUserByAnsList", method = RequestMethod.POST)
    public HttpResponseEntity tenantCreateUserByAnsList(@RequestBody Map<String, Object> map) {


        httpResponseEntity.setData(userService.tenantCreateUserByAnsList(map));
        httpResponseEntity.setCode(Constants.SUCCESS_CODE); // 一定是新增成功的
        httpResponseEntity.setMessage(Constants.CREATE_MESSAGE);
        return httpResponseEntity;
    }

}
